﻿cms.Menu = function () {

    function _getMenu(a) {
        var parent = a.parentNode;
        while (parent.tagName != "DIV")
            parent = parent.parentNode;
        return parent;
    }

    function _getCookie(name) {
        var allCookies = document.cookie.split(';');
        var cookie = '';
        var key = '';
        var value = '';
        var found = false;
        for (i = 0; i < allCookies.length; i++) {
            cookie = allCookies[i].split('=');
            key = cookie[0].replace(/^\s+|\s+$/g, '');
            if (key == name) {
                found = true;
                if (cookie.length > 1)
                    value = unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
                return value;
                break;
            }
            cookie = null;
            key = '';
        }
        if (!found)
            return null;
    }

    function _setCookie(name, value) {
        var expires = new Date();
        expires.setDate(expires.getDate() + 365);
        document.cookie = name + "=" + escape(value) + ";expires=" + expires.toGMTString() + ";path=/";
    }


    function _getUL(a) {
        var ul = a.nextSibling;
        while (ul && ul.nodeType != 1)
            ul = ul.nextSibling;
        return ul;
    }

    function _getVisibleLevels(menu) {
        var uls = menu.getElementsByTagName("ul");
        var levels = 1;
        for (var i = 0; i < uls.length; i++) {
            if (uls[i].className == "expanded") {
                var level = 1;
                var parent = uls[i].parentNode;
                while (parent && parent.tagName != "DIV") {
                    if (parent.tagName != "UL")
                        level++;
                    parent = parent.parentNode;
                }
                if (level > levels)
                    levels = level;
            }
        }
        for (var i = 0; i < menu.childNodes.length; i++) {
            if (menu.childNodes[i].tagName == "UL")
                menu.childNodes[i].className = "level" + levels;
        }
    }

    function _toggleItem(a) {
        var id = a.parentNode.id.substr(a.parentNode.id.indexOf("-") + 1); // Remove the prefix from the LI id
        var menu = _getMenu(a);
        var cookieValue = _getCookie(menu.className);
        if (cookieValue == null)
            cookieValue = "";
        expandedIDs = cookieValue.split(",");
        var ids = new Array();
        for (var i = 0; i < expandedIDs.length; i++) {
            if (expandedIDs[i] != "" && expandedIDs[i] != "NaN" && parseInt(expandedIDs[i], 10) != NaN && parseInt(expandedIDs[i], 10) != id) {
                ids[ids.length] = parseInt(expandedIDs[i], 10);
            }
        }
        var ul = _getUL(a);
        if (!ul)
            return;

        $(ul).slideToggle(100, function () {
            //alert(this.tagName); 
        });

        if (ul.className == "") {
            ul.className = "expanded";
            ids[ids.length] = id;
        }
        else
            ul.className = "";
        _setCookie(menu.className, ids.join(","));
    }

    function _openUnlinkedItemExclusively(a) {
        var ul = _getUL(a);
        if (!ul || ul.className == "expanded")
            return;
        // Get all sibling links and inactivate them
        var siblingListItems = a.parentNode.parentNode.childNodes;
        for (var i = 0; i < siblingListItems.length; i++) {
            if (siblingListItems[i] == a.parentNode) // Skip the current active li
                continue;
            var children = siblingListItems[i].childNodes;
            if (!children || children.length == 0)
                continue;
            var otherLink = children[0]; // Find link
            while (otherLink && otherLink.nodeType != 1 && otherLink.tagName != "A")
                otherLink = otherLink.nextSibling;
            otherLink.className = "";
        }
        a.className = "active";
        var expandedIDs = a.parentNode.id.substr(a.parentNode.id.indexOf("-") + 1); // Remove the prefix from the LI id
        var menu = _getMenu(a);
        var menuSettings = _menus[menu.className];
        var parent;
        var ignoreUL;
        // Collapse all sub level ULs
        var uls = menu.childNodes[0].getElementsByTagName("ul");
        for (var i = 0; i < uls.length; i++) {
            // Ignore already closed ULs
            if (uls[i].className == "")
                continue;
            // Check if the current ul is a parent to the clicked item
            ignoreUL = false;
            parent = ul.parentNode;
            while (parent.tagName != "DIV") {
                if (parent == uls[i]) {
                    ignoreUL = true;
                    break;
                }
                parent = parent.parentNode;
            }
            if (ignoreUL)
                continue;
            $(uls[i]).slideUp(menuSettings.slideDuration);
            uls[i].className = "";
            //if (uls[i].style.display == "block")
            //    uls[i].style.display = "none";
        }
        // Expand the current UL and all parent ULs
        $(ul).slideDown(menuSettings.slideDuration);
        ul.className = "expanded";
        parent = ul.parentNode;
        while (parent.tagName != "DIV") {
            if (parent.tagName == "UL") {
                var itemID = parent.parentNode.getAttribute("item");
                if (itemID != null) {
                    expandedIDs += "," + itemID;
                    parent.className = "expanded";
                    parent.style.display = "block";
                }
            }
            parent = parent.parentNode;
        }
        _getVisibleLevels(menu);
        _setCookie(menu.className, expandedIDs);
        $("body").focus();
    }

    function _openLinkedItemExclusively(a) {
        var menu = _getMenu(a);
        var expandedIDs = a.parentNode.id.substr(a.parentNode.id.indexOf("-") + 1); // Remove the prefix from the LI id
        if (expandedIDs == null)
            expandedIDs = "";
        // Expand all parent ULs
        var parent = a.parentNode;
        while (parent.tagName != "DIV") {
            if (parent.tagName == "UL") {
                var itemID = parent.parentNode.id.substr(parent.parentNode.id.indexOf("-") + 1); // Remove the prefix from the LI id
                if (itemID != null) {
                    expandedIDs += "," + itemID;
                    parent.className = "expanded";
                }
            }
            parent = parent.parentNode;
        }
        // If this item has subitems, expand this UL
        var ul = _getUL(a);
        if (ul) {
            ul.className = "expanded";
        }
        _getVisibleLevels(menu);
        _setCookie(menu.className, expandedIDs);
    }

    var _menus = {};

    function _init(menuID, behaviour) {
        _menus["cmsMenu" + menuID] = {
            behaviour: behaviour,
            slideDuration: 100
        };
        // Find the menu div by its class name
        var divs = document.getElementsByTagName("div");
        var div = null;
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className == "cmsMenu" + menuID) {
                div = divs[i];
                break;
            }
        }
        if (div == null)
            return;
        // Set up all click events on the links
        var links = div.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if (links[i].href == "javascript:void(0);") { // LinkType == Nothing
                switch (behaviour) {
                    case "Toggle":
                        iLib.Dom.AddListener(links[i], "click", function (e) {
                            e = e || window.event;
                            var target = e.target || e.srcElement;
                            _toggleItem(target);
                        });
                        break;
                    case "OpenExclusively":
                        iLib.Dom.AddListener(links[i], "click", function (e) {
                            e = e || window.event;
                            var target = e.target || e.srcElement;
                            _openUnlinkedItemExclusively(target);
                        });
                        break;
                }
            }
            else { // LinkType == Page
                switch (behaviour) {
                    case "Toggle":
                        break;
                    case "OpenExclusively":
                        iLib.Dom.AddListener(links[i], "click", function (e) {
                            e = e || window.event;
                            var target = e.target || e.srcElement;
                            _openLinkedItemExclusively(target);
                        });
                        break;
                }
            }
        }
    }

    return {
        Init: _init
    }

} ();

